<?php
/*
 * @Author: lokei
 * @Date: 2022-08-20 17:20:34
 * @LastEditors: lokei
 * @LastEditTime: 2022-08-20 19:08:50
 * @Description: 
 */

namespace App\Http\Controllers\Scrm\Qiwei;

use App\Models\Platform\ConfQiweiModel;
use GuzzleHttp;
use Illuminate\Support\Facades\Redis;

class Common
{
    public static function getAccessToken()
    {
        if (Redis::exists('qiwei_access_token')) {
            return Redis::get('qiwei_access_token');
        } else {
            $http = new GuzzleHttp\Client;
            $conf = ConfQiweiModel::first();
            $params = [
                'corpid' => $conf->corpid,
                'corpsecret' => $conf->corpsecret
            ];
            $response = $http->get('https://qyapi.weixin.qq.com/cgi-bin/gettoken', [
                'query' => $params
            ]);
            $result = json_decode($response->getBody(), true);
            if ($result['errcode'] == 0) {
                Redis::setex('qiwei_access_token', intval($result['expires_in']) - 300, $result['access_token']);
                return $result['access_token'];
            }
            return '';
        }
    }
}
